<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #rectList>
        <a-button class="mt-2 btn" @click="handleRectListAdd" v-if="isShow">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('添加整改项') }}
        </a-button>
        <BasicTable @register="registerRectListTable" @row-click="handleRectListRowClick">
          <template #rectListUpload="{ record: childRecord }">
            <BasicUpload
              v-model:value="childRecord.dataMap"
              :bizKey="childRecord.id"
              :bizType="'rectList_file'"
              :uploadType="'all'"
              :loadTime="record.__t"
              :isPreview="false"
            />
          </template>
        </BasicTable>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsProjXjPmInspectionForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicUpload } from '/@/components/Upload';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { PmInspection, pmInspectionSave, pmInspectionForm } from '/@/api/proj/xj/pmInspection';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';

  const emit = defineEmits(['success', 'register']);
  const { hasPermission } = usePermission();

  const { t } = useI18n('proj.xj.pmInspection');
  const { showMessage } = useMessage();
  const record = ref<PmInspection>({} as PmInspection);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增巡检') : t('编辑巡检'),
  }));

  let isShow = ref(false)

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('项目名称'),
      field: 'projectno',
      fieldLabel: 'name',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: {
          projStatus:2
        },
        canSelectParent: false,
        allowClear: false,
        disabled:computed(() => !isShow.value),
      },
    },
    {
      label: t('项目编号'),
      field: 'projectno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        readonly: true,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('巡检日期'),
      field: 'inspectiondate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        disabled:computed(() => !isShow.value),
      },
      required: true,
    },
    {
      label: t('巡检人'),
      field: 'inspector',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled:computed(() => !isShow.value),
      },
      required: true,
    },
    {
      label: t('巡检备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: -1,
        rows: 5,
        disabled:computed(() => !isShow.value),
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('图片上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'pmInspection_image',
        uploadType: 'image',
        isPreview: true,
        disabled:computed(() => !isShow.value),
      },
      colProps: { lg: 24, md: 24 },
      rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['pmInspection_image__len'] || 0;
              if (len == 0) reject(t('请上传图片'));
              else resolve();
            });
          },
        },
      ],
    },
    {
      label: t('巡检明细'),
      field: 'childList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rectList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerRectListTable, rectListTable] = useTable({
    actionColumn: {
      width: 40,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleRectListDelete.bind(this, record),
          },
          // auth: 'proj:xj:pmInspection:edit',
          ifShow:isShow.value,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showIndexColumn: true,
  });

  async function setRectListTableData(_res: Recordable) {
    rectListTable.setColumns([
      {
        title: t('整改措施'),
        dataIndex: 'rectificationmeasures',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('整改内容'),
        dataIndex: 'rectificationcontent',
        width: 200,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('整改期限'),
        dataIndex: 'endtime',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          showTime: false,
        },
        editRule: false,
      },
      {
        title: t('文件上传'),
        dataIndex: 'upload',
        width: 120,
        align: 'left',
        slot: 'rectListUpload',
      },
    ]);
    rectListTable.setTableData(record.value.rectList || []);
  }

  function handleRectListRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }
  function handleRectListAdd() {
    rectListTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
      rectificationmeasures: '现场整改',
    });
  }
  function handleRectListDelete(record: Recordable) {
    rectListTable.deleteTableDataRecord(record);
  }
  async function getRectList() {
    let rectListValid = true;
    let rectList: Recordable[] = [];
    for (const record of rectListTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        rectListValid = false;
      }
      rectList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of rectListTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      rectList.push({
        ...record,
        status: '1',
      });
    }
    if (!rectListValid) {
      throw { errorFields: [{ name: ['rectList'] }] };
    }
    return rectList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmInspectionForm(data);
    record.value = (res.pmInspection || {}) as PmInspection;
    if(data.projectno){
      record.value.projectno = data.projectno
      record.value.name = data.name
    }

    record.value.__t = new Date().getTime();
    
    
    setFieldsValue(record.value);
    setRectListTableData(res);
    if(record.value.isNewRecord){
      isShow.value = hasPermission(['proj:xj:pmInspection:edit'])
    }else{
      isShow.value = hasPermission(['btn:edit:xunjian'])
    }
    setDrawerProps({
      loading: false,
      showOkBtn: isShow.value ,
    });

   
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.rectList = await getRectList();
      // console.log('submit', params, data, record);
      const res = await pmInspectionSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style scoped>
  /deep/.jeesite-basic-table .ant-table-content {
    min-height: 40vh;
  }

  .btn {
    margin-bottom: 8px;
  }
</style>
